<template>
  <div class="app-container">
    <!-- 条件查询区域开始 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item :label="$t('procInst.procDefName')" prop="procDefKey">
          <jmash-select
            :placeholder="$t('procInst.procDefNamePlaceholder')"
            :data="Dict.procDict.values"
            v-model="queryParams.procDefKey"
          ></jmash-select>
        </el-form-item>
        <!-- 事项分类 -->
        <el-form-item :label="$t('task.category')" prop="category">
          <el-tree-select
            v-model="queryParams.category"
            :data="Dict.categoryCodeDict.values"
            filterable
            clearable
            check-strictly
            class="w-full"
            :render-after-expand="false"
            :placeholder="$t('task.categoryPlaceholder')"
          />
        </el-form-item>
        <el-form-item :label="$t('task.priority')" prop="priority">
          <jmash-select
            :placeholder="$t('task.priorityPlaceholder')"
            :data="Dict.priorityDict.values"
            v-model="queryParams.priority"
          ></jmash-select>
        </el-form-item>
        <el-form-item class="search-btn">
          <el-button type="primary" @click="tableHooks.handleQuery()">
            {{ $t("common.search") }}
          </el-button>
          <el-button @click="tableHooks.resetQuery()">{{
            $t("common.reset")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 条件查询区域结束 -->
    <el-card shadow="never" class="table-container">
      <!-- 按钮开始 -->
      <template #header>
        <!-- 按钮开始 -->
        <el-row justify="space-between" :span="20">
          <el-col :span="12"> </el-col>
          <el-col :span="8" align="right">
            <jmash-column-select
              v-model="tableLabel"
              label-name="flow/monitor"
            />
          </el-col>
        </el-row>
      </template>
      <!-- 按钮结束 -->

      <!-- 表格开始 -->
      <jmash-table
        class="table-top"
        ref="multipleTableRef"
        row-key="id"
        :list-loading="listLoading"
        :data="tableData"
        :table-label="tableLabel"
        @selection-change="tableSelected"
        @sort-change="handleSort"
        :is-selection="false"
      >
        <!-- suspended -->
        <template #suspended="scope">
          <span>
            {{ Dict.suspendBiz.getValue(scope.data.row.suspended.toString()) }}
          </span>
        </template>
        <template #startUserId="scope">
          {{
            rbacApi.userInfo(scope.data.row.startUserId, vueMetaEnv.APP_TENANT)
              .realName
          }}
        </template>
        <template #startTime="scope">
          <span>{{
            format(new Date(scope.data.row.startTime), "yyyy-MM-dd HH:mm:ss")
          }}</span>
        </template>
        <template #description="scope">
          <span>{{ queryProVas(scope.data.row) }}</span>
        </template>
        <template #operation="scope">
          <span
            class="el-button-color"
            @click="handleViewDiagram(scope.data.row)"
          >
            {{ $t("flow.viewDiagram") }}
          </span>
          <span
            v-hasPerm="['flow:done_inst:view']"
            class="el-button-color dropdown-left"
            @click="handleInfo(scope.data.row)"
          >
            {{ $t("common.view") }}
          </span>
          <span
            class="el-button-color dropdown-left"
            v-hasPerm="['flow:done_inst:urge']"
            @click="handleUrge(scope.data.row)"
            >{{ $t("procInst.reminders") }}</span
          >
        </template>
      </jmash-table>
      <template #footer>
        <jmash-pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:current-page="queryParams.curPage"
          v-model:page-size="queryParams.pageSize"
          @pagination="tableHooks.getList()"
        />
        &nbsp;
      </template>
    </el-card>
    <procinit-diagram
      v-if="viewDialog.visible"
      v-model="viewDialog.visible"
      :title="viewDialog.title"
      :entity-key="entityKey"
      width="900px"
    />
  </div>
</template>
<script setup lang="ts">
import { type Ref, ref, reactive, onActivated, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  type TableColumn,
  type DialogRef,
  type TableSort,
  useTableHooks,
  vueMetaEnv,
} from "jmash-core";
import { Dict } from "@/api/flow/dict";
import { format } from "date-fns";
import { rbacApi } from "jmash-rbac";
import { procApi } from "xyvcard-workflow";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
import type {
  ProcInstReq,
  FlowProcInstKey,
  FlowProcInstModel,
} from "@/api/flow/task/types";
import { doneInstApi } from "@/api/flow/doneinst/index";
import { taskApi } from "@/api/flow/task/index";
import procinitDiagram from "@/views/flow/common/procinst-diagram-dialog.vue";

const queryParams = ref<ProcInstReq>({});
// 分类层级字典
Dict.categoryCodeDict.useValues();
// 流程
Dict.procDict.useValues();

const {
  tableHooks,
  multipleTableRef,
  queryFormRef,
  listLoading,
  tableData,
  total,
} = useTableHooks(t, doneInstApi, queryParams);

let tableLabel: Ref<TableColumn[]> = ref([
  {
    label: "procInst.id",
    prop: "id",
    width: "100",
    sortable: "custom",
    isColumn: true,
  },
  {
    label: "procInst.name",
    prop: "name",
    isColumn: true,
  },
  {
    label: "procInst.processDefinitionName",
    prop: "processDefinitionName",
    sortable: "custom",
    width: "180",
    isColumn: true,
  },
  {
    label: "procInst.startUserId",
    prop: "startUserId",
    width: "120",
    slotName: "startUserId",
    columnType: "slot",
    isColumn: true,
  },
  {
    label: "procInst.startTime",
    prop: "startTime",
    width: "160",
    slotName: "startTime",
    columnType: "slot",
    sortable: "custom",
    isColumn: true,
  },
  {
    label: "procInst.businessStatus",
    prop: "businessStatus",
    width: "120",
    isColumn: true,
  },
  {
    label: "procInst.suspended",
    prop: "suspended",
    width: "110",
    slotName: "suspended",
    columnType: "slot",
    isColumn: false,
  },
  {
    label: "procInst.businessKey",
    prop: "businessKey",
    width: "120",
    isColumn: false,
  },
  {
    label: "procInst.processDefinitionId",
    prop: "processDefinitionId",
    width: "200",
    sortable: "custom",
    isColumn: false,
  },
  {
    label: "procInst.description",
    prop: "description",
    slotName: "description",
    columnType: "slot",
    isColumn: true,
  },
  {
    label: "common.operate",
    width: "200",
    slotName: "operation",
    columnType: "slot",
    fixed: "right",
    isColumn: true,
  },
]);
//查看Dialog
const viewDialog = ref({
  title: t("flow.viewDiagram"),
  visible: false,
} as DialogRef);

let entityKey = reactive<FlowProcInstKey>({});

// 详情
function handleInfo(row: FlowProcInstModel) {
  router.push({
    path: "/rawflow/doneinst/info",
    query: { taskId: row.id, processKey: row.processDefinitionKey },
  });
}

// 查看流程图
function handleViewDiagram(row: FlowProcInstModel) {
  entityKey.procInstId = row.id;
  viewDialog.value.visible = true;
}

// 行选择
function tableSelected(value: FlowProcInstModel[]) {
  tableHooks.selectionRows.value = value;
}

//处理排序
function handleSort(sort: TableSort) {
  //Flowable 排序方式.
  let orderName = "";
  if (sort.prop == "id") {
    orderName = "RES.ID_";
  } else if (sort.prop == "processDefinitionName") {
    orderName = "P.KEY_";
  } else if (sort.prop == "processDefinitionId") {
    orderName = "RES.PROC_DEF_ID_";
  } else if (sort.prop == "startTime") {
    orderName = "RES.START_TIME_";
  }
  tableHooks.handleSort(orderName, sort.order);
}

/**
 * 从子组件传过来的事件，刷新列表
 *
 * @returns {void}
 */
function refresh(value: boolean) {
  if (value) {
    tableHooks.getList();
  }
}

if (route.query.procDefId) {
  queryParams.value.procDefId = route.query.procDefId as string;
}

//查询数据.
onActivated(() => {
  tableHooks.getList();
});

/**
 * 查询流程变量并更新任务描述
 *
 * @param {FlowProcInstModel} row - 流程任务模型对象，包含流程实例ID等信息
 * @returns {string|undefined} 返回任务描述信息，如果流程实例ID不存在则返回undefined
 */

// 缓存已请求的 processInstanceId 及其结果
const processInstanceCache = new Map<string, Promise<any>>();
function queryProVas(row: FlowProcInstModel) {
  // 如果没有 processInstanceId，则直接返回
  if (!row.processInstanceId) return;

  let requestPromise: Promise<any>;

  // 检查是否已有缓存
  if (processInstanceCache.has(row.processInstanceId)) {
    // 使用缓存中的请求 Promise
    requestPromise = processInstanceCache.get(row.processInstanceId)!;
  } else {
    // 发起新请求并将其存入缓存
    requestPromise = taskApi.findProcinstId({
      procInstId: row.processInstanceId,
    });
    processInstanceCache.set(row.processInstanceId, requestPromise);
  }

  // 处理响应数据
  requestPromise.then(({ data }) => {
    row.description =
      data?.vars["description"] && data?.vars["description"].value;
  });

  return row.description;
}

// 催办
function handleUrge(row: FlowProcInstModel) {
  procApi.urge({ procInstId: row.processInstanceId }).then((res) => {
    console.log(res);
  });
}
</script>
